<template>
	<n-scrollbar class="max-h-[360px]">
		<div class="px-3">
			<AppWalletBalanceCollapse
				v-model:expand="walletStore.walletConfig.expandFiat"
				titleT="wallet.fiat">
				<div v-if="fiatList.length">
					<AppWalletBalanceItem
						v-for="item in fiatList"
						:key="item.currency"
						:item="item"
						@click="clickItem(item)" />
				</div>
				<BaseEmpty v-else class="min-h-9" emptyImg="" />
			</AppWalletBalanceCollapse>
			<AppWalletBalanceCollapse
				v-model:expand="walletStore.walletConfig.expandCrypto"
				titleT="wallet.crypto">
				<div v-if="cryptoList.length">
					<AppWalletBalanceItem
						v-for="item in cryptoList"
						:key="item.currency"
						:item="item"
						@click="clickItem(item)" />
				</div>
				<BaseEmpty v-else class="min-h-9" emptyImg="" />
			</AppWalletBalanceCollapse>
			<div class="h-[6px]" />
		</div>
	</n-scrollbar>
</template>

<script setup lang="ts">
import { computed, watch } from 'vue'
import { filter } from 'lodash-es'
import { NScrollbar } from 'naive-ui'
import { useWalletStore } from '@/store'
import { BaseEmpty } from '@/components/base'
import { showError } from '@/utils'
import AppWalletBalanceCollapse from './app-wallet-balance-collapse.vue'
import AppWalletBalanceItem from './app-wallet-balance-item.vue'

const emit = defineEmits(['update:show'])
const props = defineProps({
	searchKey: {
		type: String,
		required: true
	}
})
const walletStore = useWalletStore()
const balanceList = computed(() => {
	const { hideZeroBalance } = walletStore.walletConfig
	const searchKeyUpper = props.searchKey.toUpperCase()
	return filter(walletStore.balanceList, (item) =>
		hideZeroBalance && !(Number(item.freeAmount) > 0)
			? false
			: String(item.appName).toUpperCase().includes(searchKeyUpper)
	)
})
const fiatList = computed(() => filter(balanceList.value, { assetType: 2 }))
const cryptoList = computed(() => filter(balanceList.value, { assetType: 1 }))

const clickItem = async (item: any) => {
	try {
		emit('update:show', false)
		await walletStore.setBalanceCur(item)
	} catch (error) {
		showError(error)
	}
}

watch(
	() => props.searchKey,
	(val) => {
		if (val) {
			walletStore.walletConfig.expandFiat = true
			walletStore.walletConfig.expandCrypto = true
		}
	}
)
</script>
